#include "tcp_client.h"
#include "tcp_client_concrete.h"
#include <Windows.h>
#include "vld.h"

BOOL APIENTRY Dllmain(HANDLE hHandle, DWORD ul_reason_, PVOID pReserved)
{
	return TRUE;
}

static int gRefCount = 0;
static cmtd::TcpClient * g_cltInst = NULL;

TCPCLT_API int __stdcall TC_Init()
{
	int result = 0;
	if (g_cltInst == NULL) {
		g_cltInst = new cmtd::TcpClient();
		result = g_cltInst->Init();
		gRefCount = 1;
	}
	else {
		gRefCount++;
	}
	return result;
}

TCPCLT_API int __stdcall TC_UnInit()
{
	gRefCount--;
	if (gRefCount < 0) {
		gRefCount = 0;
	}
	if (gRefCount == 0 ) {
		if (g_cltInst) {
			delete g_cltInst;
			g_cltInst = NULL;
		}
	}
	return 0;
}

TCPCLT_API int __stdcall TC_RegisterModule(cmtd::SERVER_INFO serverInfo_, cmtd::MODULE_INFO_PTR pModuleInfo_,
	void(__stdcall *msg_callback_)(cmtd::MESSAGE_INFO), void * userData_)
{
	if (g_cltInst) {
		return g_cltInst->RegisterModule(serverInfo_, pModuleInfo_, msg_callback_, userData_);
	}
	return -1;
}

TCPCLT_API int __stdcall TC_UnRegisterModule(cmtd::UNREGISTER_PARAMETER unregisterInfo_)
{
	if (g_cltInst) {
		return g_cltInst->UnRegisterModule(unregisterInfo_);
	}
	else {
		return -1;
	}
}

TCPCLT_API int __stdcall TC_GetLastError()
{
	return 0;
}

TCPCLT_API int __stdcall TC_Fetch(cmtd::FETCH_PARAMETER fetchParam_)
{
	if (g_cltInst) {
		return g_cltInst->FetchTask(fetchParam_);
	}
	return -1;
}

TCPCLT_API int __stdcall TC_Post(cmtd::POST_PARAMETER postParam_)
{
	if (g_cltInst) {
		return g_cltInst->PostTask(postParam_);
	}
	return -1;
}

TCPCLT_API int __stdcall TC_Finish(cmtd::FINISH_PARAMETER finishParam_)
{
	if (g_cltInst) {
		return g_cltInst->FinishTask(finishParam_);
	}
	return -1;
}

TCPCLT_API int __stdcall TC_SetMessageCallback(cmtd::MESSAGE_CALLBACK_PARAMETER msgCbParam_)
{
	if (g_cltInst) {
		g_cltInst->SetMessageCallback(msgCbParam_);
	}
	return 0;
}